package com.studentbook.servlet;

import com.studentbook.bean.StudentContact;
import com.studentbook.service.StudentContactService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 按姓名查询联系人Servlet
 */
@WebServlet("/searchByName")
public class SearchByNameServlet extends HttpServlet {
    private StudentContactService contactService = new StudentContactService();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        // 获取请求参数
        String name = request.getParameter("name");
        
        if (name != null && !name.trim().isEmpty()) {
            // 按姓名查询联系人
            List<StudentContact> contactList = contactService.getContactsByName(name);
            
            // 将联系人列表和查询条件放入请求属性
            request.setAttribute("contactList", contactList);
            request.setAttribute("searchName", name);
        } else {
            // 如果没有提供姓名，查询所有联系人
            List<StudentContact> contactList = contactService.getAllContacts();
            request.setAttribute("contactList", contactList);
        }
        
        // 转发到联系人列表页面
        request.getRequestDispatcher("/list.jsp").forward(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}